<?php

namespace app\common\logic;

use think\Model;

class Chat extends Model
{
    protected $autoWriteTimestamp = true;
    protected $auto = ['uid'];

    protected function setUidAttr($value)
    {
        return getUid();
    }

    protected function setUserListAttr($value)
    {
        if (!empty($value)) {
            if (is_array($value)) return implode(',', $value);
            else return $value;
        }
        return '';
    }

    /**
     * 新增会话成员
     * @param $chatid
     * @param $users
     * @return int
     * @author wb <pithyone@vip.qq.com>
     */
    public function addUsers($chatid, $users)
    {
        $userlist_before = $this::where(['chatid' => $chatid])->value('userlist');

        if (!empty($userlist_before))
            $users = array_merge(explode(',', $userlist_before), $users);

        $userlist_after = implode(',', $users);

        $ret = $this->allowField(true)->isUpdate(true)->save(['userlist' => $userlist_after], ['chatid' => $chatid]);
        return $ret;
    }

    /**
     * 删除会话成员
     * @param $chatid
     * @param $users
     * @return bool|int
     * @author wb <pithyone@vip.qq.com>
     */
    public function delUsers($chatid, $users)
    {
        $userlist_before = $this::where(['chatid' => $chatid])->value('userlist');

        if (!empty($userlist_before)) {
            $userlist = explode(',', $userlist_before);

            foreach ($users as $val) {
                $key = array_search($val, $userlist);
                if ($key !== false) {
                    array_splice($userlist, $key, 1);
                }
            }

            $ret = $this->allowField(true)->isUpdate(true)->save(['userlist' => $userlist], ['chatid' => $chatid]);
            return $ret;
        }

        return true;
    }
}